package org.feidao.chapter81.controller;


import lombok.extern.slf4j.Slf4j;
import org.feidao.chapter81.model.HeroicFactory;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

/**
 * Created by linghufeixia on 2022-12-12.
 * Protobuf序列化和反序列化
 *
 */
@Slf4j
@RestController
@RequestMapping(value = "protobuf")
public class ProtobufController {

    @RequestMapping(value = "/saveHeroic", method = RequestMethod.GET)
    public String saveHeroic(@RequestParam(value = "id") String id,
                             @RequestParam(value = "name") String name,
                           @RequestParam(value = "remarks") String remarks){
        HeroicFactory.Heroic.Builder builder = HeroicFactory.Heroic.newBuilder();
        long lId = 0l;
        try {
            lId = Long.parseLong(id);
        }catch (Exception e){
            e.printStackTrace();
        }
        builder.setId(lId);
        builder.setName(name);
        builder.setRemarks(remarks);
        HeroicFactory.Heroic  heroic= builder.build();

        //转换成字节数组
        byte[] bytes = heroic.toByteArray();
        log.info("序列化:" + Arrays.toString(bytes));

        try {
            HeroicFactory.Heroic deserializeHeroic = HeroicFactory.Heroic.parseFrom(bytes);
            log.info("反序列化:");
            log.info("id:" + deserializeHeroic.getId());
            log.info("name:" + deserializeHeroic.getName());
            log.info("remarks:" + deserializeHeroic.getRemarks());
        }catch (Exception e){
            e.printStackTrace();
        }
        return "success";
    }
}
